package com.lizardmind.haofudoctor.test

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.support.annotation.LayoutRes
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.linxiao.framework.BR
import me.drakeet.multitype.ItemViewBinder

/**
 *
 * Created by Extends on 2017/11/29 15:45
 */
class BaseBinder<T,V:ViewDataBinding>(@LayoutRes val layoutId:Int): ItemViewBinder<T,BaseBinder.Companion.Holder>() {
    var onBind :((itemBinding:V,data:T)->Unit)?=null
    override fun onBindViewHolder(holder: Holder, item: T) {
        (holder.getBinding() as V).apply {
            setVariable(BR.item,item)
        }
//        if_onBind?.onBind(viewHolder.getBinding() as T2,realPosition,data)
        //不加这一行，刷新时会闪烁
        //当变量的值更新的时候，binding 对象将在下个更新周期中更新。这样就会有一点时间间隔，
        // 如果你像立刻更新，则可以使用 executePendingBindings 函数。
        holder.getBinding().executePendingBindings()
        onBind?.invoke(holder.getBinding()as V,item)
    }

    override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): Holder {
        return Holder(inflater.inflate(layoutId, parent, false))
    }


    companion object {
        class Holder(view: View) : RecyclerView.ViewHolder(view){
            private val b: ViewDataBinding by lazy {
                DataBindingUtil.bind<ViewDataBinding>(itemView)
            }

            fun getBinding(): ViewDataBinding {
                return b
            }
        }
    }
}